#include <string>
#include <vector>
#include <cstdio>
#include <cstring>
#include "pdf.h"

using namespace std;

/* 初始化PDF签名 */
void mypdf_init_info();

/* 创建PDF */
struct pdf_doc *mypdf_create();
/* 保存PDF */
void mypdf_save(struct pdf_doc *p, const char *filename);

/* 创建新的页面 */
void mypdf_new_page(struct pdf_doc *p);

/* 输出文字 */
void mypdf_print(struct pdf_doc *p, const char *text, const float x, const float y);

/* 每行上边界之间的距离 */
const float line_gap = 32;
/* 纸张大小 */
const float paper_width = PDF_A4_WIDTH;
const float paper_height = PDF_A4_HEIGHT;
/* PDF字体 */
const char *font = "Courier";
const float font_size = 24.0;
/* PDF签名配置 */
struct pdf_info info;
bool info_init = false;

/* 输出到PDF */
int mypdf_out(string &filename, vector<string> &text,
              const int lines_per_page, const float left, const float top)
{
    if(!info_init) mypdf_init_info();
    struct pdf_doc *p = mypdf_create();
    if(NULL == p) return -1;
    int nr_page = text.size() / lines_per_page;
    nr_page += !!(text.size() % lines_per_page);
    for(int i = 0; i < nr_page; ++i)
    {
        /* 外层控制页数 */
        mypdf_new_page(p);
        for(int j = 0; j < lines_per_page; ++j)
        {
            /* 内层控制行数 */
            mypdf_print(p, text[i * lines_per_page + j].c_str(), left, top + j * line_gap);
        }
    }
    mypdf_save(p, filename.c_str());
    return 0;
}

/* 初始化PDF签名 */
void mypdf_init_info()
{
    strcpy(info.author, "LAW");
    strcpy(info.creator, "LAW");
    strcpy(info.date, "Today");
    strcpy(info.producer, "LAW");
    strcpy(info.subject, "\0");
    strcpy(info.title, "LAW - Report");
    info_init = true;
}

/* 创建PDF */
struct pdf_doc *mypdf_create()
{
    struct pdf_doc *p = pdf_create(paper_width, paper_height, &info);
    if(NULL == p) return NULL;
    pdf_set_font(p, font);
    return p;
}

/* 保存PDF */
void mypdf_save(struct pdf_doc *p, const char *filename)
{
    pdf_save(p, filename);
    pdf_destroy(p);
}

/* 创建新的页面 */
void mypdf_new_page(struct pdf_doc *p)
{
    pdf_append_page(p);
}

/* 输出文字 */
void mypdf_print(struct pdf_doc *p, const char *text, const float x, const float y)
{
    /* PDF坐标以左下角为原点，x轴向右，y轴向上 */
    /* 此处进行y轴变换 */
    pdf_add_text(p, NULL, text, font_size, x, paper_height - y, PDF_BLACK);
}